package com.zhong.subject.infra.basic.untils;

import com.alibaba.druid.filter.config.ConfigTools;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 数据库加密until
 */
public class DruidEncryptUntil {
    private static String publicKey;
    private static String privateKey;
    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            publicKey = keyPair[1];
            System.out.println("privateKey：" + privateKey);
            System.out.println("publicKey：" + publicKey);
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 加密
     * @param plainText 需要加密的字符串
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText) throws Exception {
        String encrypt = ConfigTools.encrypt(privateKey, plainText);
        System.out.println("encrypt：" + encrypt);
        return encrypt;
    }

    /**
     * 解密
     * @param encryptText 需要解密的字符串
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptText) throws Exception {
        String decrypt = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decrypt：" + decrypt);
        return decrypt;
    }

    public static void main(String[] args) throws Exception {
        String encrypt = encrypt("1023");
        String decrypt = decrypt(encrypt);
    }

}
